package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
@Slf4j
public class VMStatusHandler implements MsgHandler {
    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;

    @Override
    public void process(String jsonMsg) throws IOException {
        var vmStatusContract= JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        if(vmStatusContract==null || vmStatusContract.getStatusInfo()==null
        ||vmStatusContract.getStatusInfo().size()<=0){
            return;
        }
        if(vmStatusContract.getStatusInfo().stream().anyMatch(s->s.isStatus()==false)){
            try {
                var vmInfo=vmService.getVMInfo(vmStatusContract.getInnerCode());
                if (vmInfo==null){
                    return;
                }
                var userId=taskService.getLeastUser(vmInfo.getRegionId(),true);
                if(userId!=0){
                    var task = new TaskViewModel();
                    task.setUserId(userId);
                    task.setInnerCode(vmStatusContract.getInnerCode());
                    task.setProductType(VMSystem.TASK_TYPE_REPAIR);
                    task.setCreateType(0);
                    task.setDesc(jsonMsg);
                    task.setAssignorId(0);
                    taskService.createTesk(task);
                }
            } catch (Exception e) {
                log.error("创建自动维修工单失败，msg is:"+jsonMsg);
            }
        }
    }
}
